﻿using SixLabors.ImageSharp;

namespace MicroCloud.Utils
{
    /// <summary>
    /// 图像扩展方法
    /// </summary>
    public static class ImageExtensions
    {
        /// <summary>
        /// 将Image转换为Base64字符串
        /// </summary>
        /// <param name="img">待处理的图像</param>
        /// <param name="format">图像格式</param>
        /// <returns></returns>
        public static string ToBase64String(this Image img, ImageFormat format = ImageFormat.Png)
        {
            var base64String = "";
            using MemoryStream ms = new();
            switch (format)
            {
                case ImageFormat.Bmp:
                    img.SaveAsBmp(ms);
                    base64String = "data:image/bmp;base64,";
                    break;
                case ImageFormat.Gif:
                    img.SaveAsGif(ms);
                    base64String = "data:image/gif;base64,";
                    break;
                case ImageFormat.Jpeg:
                    img.SaveAsJpeg(ms);
                    base64String = "data:image/jpeg;base64,";
                    break;
                case ImageFormat.Png:
                    img.SaveAsPng(ms);
                    base64String = "data:image/png;base64,";
                    break;
                case ImageFormat.Tga:
                    img.SaveAsTga(ms);
                    base64String = "data:image/tga;base64,";
                    break;
            }
            byte[] bytes = ms.ToArray();
            return $"{base64String}{bytes.ToBase64String()}";
        }

        /// <summary>
        /// 转换成图片
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static Image ToImage(this byte[] bytes)
        {
            MemoryStream ms = new(bytes)
            {
                Position = 0
            };
            Image img = Image.Load(ms);
            ms.Close();
            return img;
        }
    }

}
